#include "wl_ext_mem.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

// Malloc memory
void* wl_ext_malloc(unsigned int size) {
    return malloc(size);
}

// Realloc memory
void* wl_ext_realloc(void* ptr, unsigned int size) {
    return realloc(ptr, size);
}

// Free memory
void wl_ext_free(void* ptr) {
    free(ptr);
}

// Malloc memory, 2nd version
void* wl_ext_malloc_2(unsigned int size) {
    return malloc(size);
}

// Realloc memory, 2nd version
void* wl_ext_realloc_2(void* ptr, unsigned int size) {
    return realloc(ptr, size);
}

// Free memory, 2nd version
void wl_ext_free_2(void* ptr) {
    free(ptr);
}

// Get memory size of free in system
int wl_ext_mem_freesize(void) {
    // This function is not implemented in standard C library
    // We can use the following code to get an estimate of free memory
    FILE* fp = fopen("/proc/meminfo", "r");
    if (fp == NULL) {
        return -1;
    }

    char line[256];
    int free_memory = 0;
    while (fgets(line, sizeof(line), fp)) {
        if (sscanf(line, "MemFree: %d kB", &free_memory) == 1) {
            break;
        }
    }

    fclose(fp);
    return free_memory * 1024; // convert kB to bytes
}